package com.srkj.activiti.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * com.srkj.activiti.controller
 * Created by zhangshaoxiong
 * data : 2018 17 48 17:48
 */
@Controller
@RequestMapping("/processModel")
public class ProcessModelController {
    private static final Logger logger = Logger.getLogger(ProcessModelController.class);

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    ObjectMapper objectMapper;
    /**
     * 跳转模型列表
     * @return
     */
    @RequestMapping(value = "/toListModel")
    public String toListModel(){
        return "model/modellist";
    }

    @RequestMapping("/listModel")
    @ResponseBody
    public List<Model> modelList(){
        List<Model> list = repositoryService.createModelQuery().list();
        return list;
    }

    /**
     *
     * @param name
     * @param key
     * @param des
     */
    @RequestMapping("/createModel")
    public String createModel(String name, String key, String des,
                            HttpServletRequest request) throws Exception{
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespance", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();
            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            des = StringUtils.defaultString(des);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, des);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
        return "redirect:/static/modeler.html?modelId="+modelData.getId();
    }



    @PostMapping(value = "/goActiviti")
    public String goActiviti(String name, String key, String description) throws UnsupportedEncodingException {
        Model model = repositoryService.newModel();

        int revision = 1;
        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);

        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());

        repositoryService.saveModel(model);
        String id = model.getId();

        //完善ModelEditorSource
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace",
                "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.put("stencilset", stencilSetNode);
        repositoryService.addModelEditorSource(id, editorNode.toString().getBytes("utf-8"));
        return "redirect:/static/modeler.html?modelId=" + id;
    }

    /**
     * 修改流程
     */
    @GetMapping("/update")
    public void edit(String modelId, HttpServletRequest request, HttpServletResponse response)
    {
        try {
            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId="+modelId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除模型
     */
    @PostMapping("/delete")
    @ResponseBody
    public void delete(String modelId){
        try {
            repositoryService.deleteModel(modelId);
        }catch (Exception e){
            e.getMessage();
        }
    }

    /**
     * 导出model的xml文件
     * @param modelId
     * @param response
     */
    @RequestMapping(value = "/export")
    public void export(String modelId, HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
            byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

            ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
            IOUtils.copy(in, response.getOutputStream());
            String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();
        } catch (Exception e) {
            logger.error("导出model的xml文件失败：modelId={}" + modelId, e);
        }
    }
    /**
     * 根据Model部署流程
     * @param modelId
     * @param
     * @return
     */
    @RequestMapping(value = "/deploy")
    public void deploy(String modelId) {
        try {
            //根据id获取model
            Model modelData = repositoryService.getModel(modelId);
            //repositoryService获取字节数组
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;
            //获取BpmnModel
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            //获取xml.bpmn
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            //获取名称
            String processName = modelData.getName() + ".bpmn20.xml";
            //部署
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();
        } catch (Exception e) {
            logger.error("根据模型部署流程失败：modelId={}" + modelId, e);
        }
    }
}
